#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

class UdpClient
{
private:
    void _initClient()
    {
        // 1.create a socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cerr << "Client init socket error" << std::endl;
        }

        // 2.construct the socket message of destination host
        _server = new struct sockaddr_in;
        _server->sin_family = AF_INET;
        _server->sin_port = htons(_serverport);
        _server->sin_addr.s_addr = inet_addr(_serverip.c_str());

        // 3.no explicit binding the _sockfd and (network message = ip + port)
        // When a client sends data for the first time, the OS automatically and randomly bind the client to prevent port conflict.
        // just call UdpClient::start() to send message
    }

public:
    UdpClient(const std::string& serverip, uint16_t serverport)
            :_serverip(serverip), _serverport(serverport)
    {
        _initClient();
    }
    ~UdpClient()
    {
        delete _server;
    }

public:
    void start()
    {
        std::string message;
        while(true)
        {
            std::cout << "Please Enter Message# ";
            std::getline(std::cin, message);
            sendto(_sockfd, message.c_str(), message.size(),
                     0, reinterpret_cast<sockaddr*>(_server), sizeof(*_server));

            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            char buffer[1024];
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1,
                             0, reinterpret_cast<sockaddr*>(&peer), &len);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cerr << "client get echo from server: " << buffer << std::endl;
            }
        }
    }

private:
    int _sockfd;
    std::string _serverip;
    uint16_t _serverport;
    struct sockaddr_in* _server;
};